package com.cimpm.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cimpm.permission.entity.Organization;
import com.cimpm.permission.entity.User;
import com.cimpm.permission.entity.UserOrganizationMapper;
import com.cimpm.permission.mapper.UserMapper;
import com.cimpm.permission.mapper.UserOrganizationMapperMapper;
import com.hby.common.callback.AutoProcessControllerPart;
import com.hby.common.entities.aspect.parameter.MapperParam;
import com.hby.common.entities.aspect.parameter.ParamConverter;
import com.hby.common.entities.aspect.parameter.ServiceInfo;
import com.hby.common.exceptions.AutoException;
import com.hby.common.exceptions.ExceptionEnum;
import com.hby.common.services.Impl.mian.AutoEntityServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

@Service
public class OrganizationServiceImpl extends AutoEntityServiceImpl<Organization> {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserOrganizationMapperMapper userOrganizationMapperMapper;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private UserOrganizationMapperServiceImpl userOrganizationMapperService;


    @Override
    public void customService(AutoProcessControllerPart autoProcessControllerPart, ServiceInfo serviceInfo) throws Throwable {

    }

    @Override
    public void addEntityOtherToRedis(Organization entity) {

    }

    @Override
    public void delEntityOtherFromRedis(Organization entity) {

    }


    public Object getUsersHasNoOrganize(ParamConverter param,Integer userId,String userName) throws Throwable{
//        Integer countInRedis = userService.getAllEntityNum();
//        Integer countInDb = userService.mapper.selectCount(null);
//        if (!countInRedis.equals(countInDb)) {
//            List<User> entities = new ArrayList<>();
//            try {
//                entities = userService.mapper.selectList(null);
//            } catch (Exception e) {
//                throw new AutoException(ExceptionEnum.JDBC, "数据库查询失败，@getAllEntitiesToRedis()，+ " + e.getMessage()); //检查实体类有没有空构造方法
//            }
//            redisUtil.getKeysBeginWith("user*").forEach(redisUtil::del);
//            for (User entity : entities) {
//                addUserToRedis(entity);
//            }
//        }
//        Set<Object> userIdsObj = redisUtil.sGet("userIds");
//        Integer[] array = new Integer[userIdsObj.size()];
//        array = userIdsObj.toArray(array);
//        List<Integer> userIds = Arrays.asList(array);
//################################
//        QueryWrapper<User> userWrapper = new QueryWrapper<>();
//        userWrapper.select("DISTINCT id").orderBy(true, true,"real_name");
//        List<User> users = userService.mapper.selectList(userWrapper);
//        List<Integer> userIds = new ArrayList<>();
//        for (User user:users){
//            userIds.add(user.getId());
//        }
//
//        QueryWrapper<UserOrganizationMapper> mapperWrapper = new QueryWrapper<>();
//        mapperWrapper.select("DISTINCT user_id");
//        List<UserOrganizationMapper> UserOrganizationMappers = userOrganizationMapperService.mapper.selectList(mapperWrapper);
//
//        listSubtraction(userIds,subIds);


        QueryWrapper<UserOrganizationMapper> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT user_id");
        List<Integer> integers = userOrganizationMapperService.mapper.selectSingleField(Integer.class, wrapper);
        //List<Integer> integers = userOrganizationMapperService.mapper.selectSingleField(Integer.class, mapperWrapper);
        return integers;
//        List<Integer> userIds = userMapper.getUserIds();
//        List<Integer> subIds = userOrganizationMapperMapper.getUserIds();
//        List<Integer> resIds = listSubtraction(userIds, subIds);
//        List<User> users = new ArrayList<>();
//        for (Integer id:resIds){
//            User entityFromId = userService.getEntityFromId(id);
//            users.add(entityFromId);
//        }
//        return users;
    }

    public Object searchUsersByKey(ParamConverter param,Integer userId,String userName) throws Throwable{
        String key = param.getString("key");
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("real_name",key).orderBy(true,true,"real_name");
        List<User> users = userService.mapper.selectList(wrapper);
        for (User user:users){
            user.setPwd(null);
        }
        return users;
    }

    public Object getUsersByOrganization(ParamConverter param, Integer userId, String userName) throws Throwable {
        Integer organizationId = param.getInt("organizationId");
        List<User> users = userOrganizationMapperService.getSecondaryEntitiesFromPrimaryId(organizationId);
        for (User user : users) {
            user.setPwd(null);
        }
        return users;
    }

    @Transactional(rollbackFor = Exception.class)
    public Object addOrganization(ParamConverter param, Integer userId, String userName) throws Throwable {
        try {
            List<Integer> userIds = param.getArrayList("userIds", Integer.class);
            Integer organizationId = param.getInt("organizationId");
            for (Integer id : userIds) {
                Integer primaryIdFromSecondaryId = userOrganizationMapperService.getPrimaryIdFromSecondaryId(id);
                if (primaryIdFromSecondaryId != null) throw new AutoException(ExceptionEnum.JDBC, id + "用户已配置过职务");
                userOrganizationMapperService.addMapper(new MapperParam(organizationId, id));
            }
            return "添加成功";
        }
        catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return e;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Object editOrganization(ParamConverter param, Integer userId, String userName) throws Throwable {
        try {
            List<Integer> userIds = param.getArrayList("userIds", Integer.class);
            Integer organizationId = param.getInt("organizationId");
            userOrganizationMapperService.editSecFetch(organizationId, userIds);
            return "修改成功";
        }
        catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return e;
        }
    }

    private void addUserToRedis(User entity) {
        //id
        Integer entityId = entity.getId();
        redisUtil.set("userId:" + entityId, entity);
        redisUtil.sSet("userIds", entityId);
        //唯一字段
        redisUtil.set("userName:" + entity.getName(), entityId);
        try {
            userService.addEntityOtherToRedis(entity);
        } catch (Exception e) {
            throw new AutoException(ExceptionEnum.REDIS, "自定义加redis方法异常");
        }
    }


}
